package com.example.springboot.service.Impl;

import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Book;
import com.example.springboot.entity.Borrow;
import com.example.springboot.entity.User;
import com.example.springboot.entity.revert;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.BookMapper;
import com.example.springboot.mapper.BorrowMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.BorrowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class BorrowServiceImpl implements BorrowService {

    @Resource
    private BorrowMapper borrowMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BookMapper bookMapper;


    @Override
    public List<Borrow> list() {
        return borrowMapper.list();
    }

    @Override
    public PageInfo<Borrow> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Borrow> borrows = borrowMapper.listByCondition(baseRequest);
        for (Borrow borrow : borrows) {
            LocalDate returnDate = borrow.getReturnDate();
            LocalDate now = LocalDate.now();
            if (now.plusDays(1).isEqual(returnDate)){
                borrow.setNote("即将过期");
            }
            else if (now.isEqual(returnDate)){
                borrow.setNote("已到期");
            }
            else if (now.isAfter(returnDate)){
                borrow.setNote("已过期");
            }
            else{
                borrow.setNote("正常");
            }
        }
        PageInfo<Borrow> BookPageInfo = new PageInfo<>(borrows);
        return BookPageInfo;
    }

    @Override
    @Transactional
    public void save(Borrow obj) {
        //1.判断用户是否存在或被禁用
        Integer userId = obj.getUserId();
        User user = userMapper.getById(userId);
        if (Objects.isNull(user)){
            throw  new ServiceException("没有该用户");
        }
        //2.判断图书数量是否充足
        String bookNo = obj.getBookNo();
        Book book = bookMapper.getByBookNo(bookNo);
        if (book.getNums()<=0){
            throw new ServiceException("图书数量不足,请联系管理员");
        }
        //3.判断用户积分是否充足
        Integer account = user.getAccount() - obj.getScore() * obj.getDays();
        log.info("account:{}",account);
        if (account < 0){
            throw new ServiceException("余额不足,请充值!");
        }
        //4.更新余额
        userMapper.updateUserAccount(obj.getUserId(),account);
        //5.更新书籍数量
        bookMapper.updateNum(book.getId());
        //6.更新借书数据
        obj.setReturnDate(LocalDate.now().plus(obj.getDays(), ChronoUnit.DAYS));
        borrowMapper.save(obj);
    }

    @Override
    public PageInfo<revert> pageRevert(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<revert> reverts = borrowMapper.listRevertByCondition(baseRequest);
        PageInfo<revert> revertPageInfo = new PageInfo<>(reverts);
        return revertPageInfo;
    }

    @Override
    @Transactional
    public void saveRevert(revert obj) {
        //修改借书状态
        obj.setStatus("已归还");
        borrowMapper.updateStatus("已归还",obj.getId());
        //修改图书数量
        bookMapper.updateRevertNum(obj.getBookNo());
        obj.setRealDate(LocalDate.now());
        borrowMapper.saveRevert(obj);
        //归还和扣除用户积分
        Book book = bookMapper.getByBookNo(obj.getBookNo());
        if (book != null){
            long until =0 ;
            if (obj.getRealDate().isBefore(obj.getReturnDate())){
                until = obj.getRealDate().until(obj.getReturnDate(), ChronoUnit.DAYS);
            }else if (obj.getReturnDate().isAfter(obj.getReturnDate())){
                until = -obj.getReturnDate().until(obj.getRealDate(), ChronoUnit.DAYS);
            }
            int score =(int) until * book.getScore(); //获取待归还的积分
            User user = userMapper.getById(obj.getUserId());
            int account = user.getAccount() + score;
            user.setAccount(account);
            if (account<0){
                //锁定账号
                user.setStatus(false);
            }
            userMapper.updateById(user);

        }

    }

    @Override
    public Borrow getById(Integer id) {
        Borrow Borrow = borrowMapper.getById(id);
        return Borrow;
    }

    @Override
    public void update(Borrow obj) {
        obj.setUpdatetime(LocalDate.now());
        borrowMapper.updateById(obj);
    }

    @Override
    public void deleteById(Integer id) {
        borrowMapper.deleteById(id);
    }

    @Override
    public void deleteRevertById(Integer id) {
        borrowMapper.deleteRevertById(id);
    }


}
